const Bus = {
    $events: {},

    $on(type, fun) {
        let res = ""
        if (type && typeof type == "string" && fun && typeof fun == "function") {
            let events = this.$events[type]
            if (events) {
                let index = events.findIndex(null)
                if (index > -1) {
                    res = `${String(index)}${type}`
                    events[index] = fun
                } else {
                    events.push(fun)
                }
            } else {
                this.$events[type] = [fun]
                res = `0${type}`
            }

        }
        return res
    },

    $emit(type, ...args) {
        if (type && typeof type == "string") {
            let events = this.$events[type]
            if (events) {
                events.forEach(fun => {
                    if (fun && typeof fun == "function") {
                        fun(...args)
                    }
                })
            }
        }
    },

    $off(type, fun) {
        if (type && typeof type == "string" && fun) {
            let events = this.$events[type]
            if (events) {
                if (typeof fun == "string") {
                    let indexStr = fun.replace(type, '')
                    let index = parseInt(indexStr)
                    events[index] = null
                }
                if (typeof fun == "function") {
                    events.forEach(item => {
                        if (item == fun) {
                            item = null
                        }
                    })
                }
            }
        }
    }
}

export default Bus